<template>
  <el-container>
    <el-header>
      <div class="app-container">
        <div class="filter-container">
          <el-button v-waves size="mini" type="primary" plain icon="el-icon-plus" @click="handleCreate">New File</el-button>
          <!-- show column popover -->
          <el-popover placement="bottom" width="150" trigger="click">
            <el-checkbox v-model="showRows.parentPath" class="filter-item" @change="tableKey = tableKey + 1">Directory</el-checkbox>
            <el-checkbox v-model="showRows.physicalAddress" class="filter-item" @change="tableKey = tableKey + 1">Store Path</el-checkbox>

            <i slot="reference" class="el-icon-setting ml10" />
            <!-- <el-button slot="reference" v-waves size="mini" type="primary" plain style="margin-left: 10px;" icon="el-icon-setting" /> -->
          </el-popover>
          <svg-icon icon-class="net-disk" class="ml10" @click="handleSpaceAttribute(space)" />

          <el-input v-model="searchQuery.fileName" placeholder="Search your files in current space" clearable style="width: 30%;float: right;" size="mini" @keyup.enter.native="handleFilter">
            <i slot="suffix" class="el-input__icon el-icon-search" style="cursor: pointer;" @click="handleFilter" />
          </el-input>
        </div>
        <FileBreadcrumb ref="fileBreadcrumb" @handleBreadcrumb="handleBreadcrumb" />
      </div>
    </el-header>
    <el-main>
      <el-table :key="tableKey" v-loading="listLoading" :data="list" size="mini" fit highlight-current-row style="width: 100%" @row-contextmenu="contextmenu">
        <el-table-column sortable prop="fileName" label="File Name">
          <template slot-scope="scope">
            <a @click="handleFileName(scope.row)">
              <svg-icon :icon-class="getIcon(scope.row)" style="font-size:25px;" />
              <span class="file-name">{{ scope.row.fileName }}</span>
            </a>
          </template>
        </el-table-column>

        <el-table-column align="center" label="File Size">
          <template slot-scope="{ row }">
            <span>{{ row.fileSize | formatCapacity() }}</span>
          </template>
        </el-table-column>

        <el-table-column v-if="showRows.physicalAddress" align="center" label="Store Path" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.physicalAddress }}</span>
          </template>
        </el-table-column>

        <el-table-column v-if="showRows.parentPath" align="center" label="Directory" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.parentPath }}</span>
          </template>
        </el-table-column>

        <el-table-column width="180px" align="center" prop="modify_at" sortable label="UpdateTime">
          <template slot-scope="scope">
            <span>{{ scope.row.modifyAt | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top:5px; margin-left: 15px;">
        <el-button v-show="hasMore" v-waves type="text" icon="el-icon-refresh" @click="searchMore()">show more</el-button>
        <span style="color: #909399;font-size: 12px;">total {{ total }} records</span>
      </div>
      <context-button v-if="menuVisible" ref="contextbutton" @foo="foo" @handleEdit="handleEdit" @handleMove="handleMove" @handleDelete="handleDelete" @handleAttribute="handleFileAttribute" />
      <LogicFile ref="dialog" @complete="complete" />
      <SpaceAttribute ref="attributeDialog" />
      <FileAttribute ref="fileAttributeDialog" />
    </el-main>
  </el-container>
</template>

<script>
import { fetchAll, fetchList, deleteAccountPassword } from '@/api/usr/logic-file'
import contextButton from './components/Contextmenu'
import waves from '@/directive/waves' // waves directive
import FileBreadcrumb from './components/FileBreadcrumb'
import LogicFile from './components/LogicFile'
import SpaceAttribute from '@/views/usr/memory-space/components/SpaceAttribute'
import FileAttribute from './components/FileAttribute'

export default {
  name: 'SpaceHome',
  directives: { waves },
  components: { FileBreadcrumb, contextButton, LogicFile, SpaceAttribute, FileAttribute },
  data() {
    return {
      tableKey: 0,
      showRows: {
        physicalAddress: false,
        parentPath: false
      },
      list: null,
      listLoading: true,
      listQuery: {
        spaceId: undefined,
        parentPath: undefined
      },
      searchQuery: {
        spaceId: undefined,
        fileName: undefined,
        current: 1,
        size: 100
      },
      isSearch: false,
      total: 0,
      breadcrumbs: null,
      listCache: new Map(),
      menuVisible: false,
      dialogFormVisible: false,
      space: null
    }
  },
  computed: {
    categories() {
      return this.$store.getters.dictionaries.filter((category) => category.dictGroup === 'file_category')
    },
    hasMore() {
      return this.isSearch && this.total > this.searchQuery.current * this.searchQuery.size
    }
  },
  created() {
    const row = this.$route.params
    this.space = row
    this.listQuery.parentPath = '/'
    this.listQuery.spaceId = row.id
    this.searchQuery.spaceId = row.id
    this.getAll()
    this.setTagsViewTitle(row.spaceName)
  },
  methods: {
    getAll() {
      this.isSearch = false
      this.listLoading = true
      fetchAll(this.listQuery)
        .then((response) => {
          this.list = response.result
          this.listCache.set(this.listQuery.parentPath, response.result)
          this.listLoading = false
          this.total = this.list.length
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    getIcon(row) {
      if (row.isDir) {
        return 'folder'
      }
      if (!row.category) {
        return 'file-unknown'
      }
      const cate = this.categories.find((category) => category.code === row.category.toString())
      return (cate && cate.reserved1) || 'file-unknown'
    },
    handleCreate() {
      this.$refs.dialog.$emit('open', false, { spaceId: this.listQuery.spaceId, parentPath: this.listQuery.parentPath })
    },
    /**
     * 新增或更新完成时的回调函数
     *
     * @param {Boolean} isEdit 是否为编辑
     * @param {Object} row 新增或更新后的行
     */
    complete(isEdit, row) {
      if (isEdit) {
        this.getAll()
      } else {
        this.list = [row, ...this.list]
        this.listCache.set(this.listQuery.parentPath, this.list)
      }
    },
    handleFilter() {
      this.searchQuery.current = 1
      this.isSearch = true
      this.getList()
      const path = '/' + 'search "' + this.searchQuery.fileName + '"'
      this.$refs.fileBreadcrumb.$emit('setBreadcrumb', path)
    },
    searchMore() {
      console.log('more')
      this.searchQuery.current++
      this.getList(true)
    },
    getList(isMore) {
      this.listLoading = true
      fetchList(this.searchQuery)
        .then((response) => {
          if (isMore) {
            response.result.list = [...this.list, ...response.result.list]
          }
          this.list = response.result.list
          this.total = response.result.total
          this.listLoading = false
        })
        .catch(() => {
          this.listLoading = false
        })
    },
    /**
     * 处理面包屑点击事件
     *
     * @param {Object} item
     */
    handleBreadcrumb(item) {
      this.listQuery.parentPath = item.parentPath
      const tmp = this.listCache.get(item.parentPath)
      if (tmp) {
        this.list = [...tmp]
      } else {
        this.getAll()
      }
    },
    /**
     * 处理文件名点击事件
     * @param {Object} row
     */
    handleFileName(row) {
      const path = row.parentPath
      // if (!path.endsWith('/')) {
      //   path += '/'
      // }
      this.listQuery.parentPath = path + row.fileName + '/'
      this.$refs.fileBreadcrumb.$emit('setBreadcrumb', this.listQuery.parentPath)
      this.getAll()
    },
    contextmenu(row, column, event) {
      this.menuVisible = false
      this.menuVisible = true
      // 阻止右键默认行为
      event.preventDefault()
      this.$nextTick(() => {
        this.$refs.contextbutton.init(row, column, event)
      })
    },
    foo() {
      // 取消鼠标监听事件 菜单栏
      this.menuVisible = false
      document.removeEventListener('click', this.foo)
    },
    handleEdit(row) {
      console.log('handleEdit')
      this.$refs.dialog.$emit('open', true, row)
    },
    handleMove(row) {
      this.$message({
        type: 'success',
        message: 'Coming soon!'
      })
    },
    handleDelete(id) {
      this.$confirm('Confirm delete record?', 'Warning', {
        confirmButtonText: 'Confirm',
        cancelButtonText: 'Cancel',
        type: 'warning'
      }).then(() => {
        deleteAccountPassword(id).then((response) => {
          console.log(response)
          this.$message({
            type: 'success',
            message: 'deleted successfully!'
          })
          this.getAll()
        })
      })
    },
    handleSpaceAttribute(row) {
      this.$refs.attributeDialog.$emit('open', row)
    },
    handleFileAttribute(row) {
      this.$refs.fileAttributeDialog.$emit('open', row)
    },
    setTagsViewTitle(name) {
      const tmp = Object.assign({}, this.$route, { title: name })
      this.$store.dispatch('tagsView/updateVisitedView', tmp)
      document.title = tmp.title
    }
  }
}
</script>

<style lang="scss" scoped>
.el-main {
  height: calc(100vh - 144px);
  padding: 0px 15px 20px 15px !important;
  .file-name {
    margin-left: 2px;
    &:hover {
      color: #409eff;
    }
  }
}
.el-header {
  // height: 90px !important;
  .app-container {
    padding: 5px 0px 5px !important;
    .ml10 {
      color: #409eff;
      margin-left: 10px;
    }
  }
}
</style>
